<?php


namespace app\api\controller\v22;


use app\api\controller\v2\Auth;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZlSynastryReport;
use app\common\lib\ConfigManage;
use app\common\model\Recode;
use \Exception;
use think\response\Json;

class SynastryReport extends Auth
{
    /**
     * 获取合盘下单介绍
     * @return Json
     * @throws Exception
     */
    public function getDetails(): Json
    {
        $srid = input('srid/d', 0);

        if ($srid !== 1)
        {
            return show(config('code.error'), '未知的商品');
        }
        $rid = input('rid/d', 0);
        if ($rid)
        {
            $recode = (new Recode())->getRecode(['id' => $rid]);
            if (!$recode || (int)$recode['uid'] !== $this->user['id'])
            {
                return show(config('code.error'), '档案不存在');
            }
        }

        $NatalReportModel = new \app\common\cachemodel\NatalReport();
        //获取商品类型
        // $goodData = (new NatalGoods())->getGoods(); // 合盘报告暂时不显示 推荐报告信息
        $goodData = [];
        // 判断当前解锁状态 本命报告
        $unlockReport = $rid ? $NatalReportModel->getNatalReport2($recode) : [];
        // $unlockReport = $rid ? $NatalReportModel->getNatalReport($this->user['id'], $rid) : [];
        $orderModel = new \app\common\cachemodel\Orders();
        $unlockingData = [];
        $lockData = [];
        $unlockData = [];
        $headerBg = '';
        $headerBgX = '';
        $relationList = [];
        $defaultData = null;
        $activingModel = new ZhunleActivity();
        // 获取合盘报告商品
        $synastryReportGoods = (new \app\common\cachemodel\Goods())->GoodsTypeInfo(17);
        $goodData = array_merge($synastryReportGoods, $goodData);
        //获取报告商品图片
        $reportImage = ConfigManage::natalReportGoodImage(1);
        foreach ($goodData as $key => $item)
        {
            $discount_price = null;
            $timeRange = null;
            $totalUnlockNum = 0;
            $goodType = (isset($item['good_type']) && $item['good_type'] === 17) ? 17 : 7;
            if ($goodType === 17)
            {
                if ((int)$item['srid'] === $srid)
                {
                    $headerBg = $item['header_bg'];
                    $headerBgX = $item['header_bg_x'];
                    $relationList = $item['relation_list'];
                    foreach ($relationList as $relationKey => $relationItem)
                    {
                        // 获取当前关系解锁数量
                        $unlockNum = $orderModel->getTotalPrepaidOrder($goodType, $srid, $relationKey);
                        $relationList[$relationKey]['unlock_num'] = $relationItem['base_num'] + $unlockNum;
                        $totalUnlockNum += $relationList[$relationKey]['unlock_num'];
                        $goodsList = [];
                        foreach ($relationItem['gids'] as $gid)
                        {
                            $timeRange = null;
                            // 获取活动商品信息
                            $activing = $activingModel->getActivingGood($goodType, $gid);
                            if ($activing)
                            {
                                $actiGids = explode(',', $activing['gids']);
                                if (in_array($gid, $actiGids, false))
                                {
                                    $discount_price = sprintf('%.2f', $item['good_list'][$gid]['now_prize'] * $activing['attr']);
                                    $timeRange = $activing['end_time'] - time();
                                }
                            }

                            $goodsList[] = [
                                'gid' => $gid,
                                'gname' => $item['good_list'][$gid]['name_desc'],
                                'price' => $discount_price ?? $item['good_list'][$gid]['now_prize'],
                                'active_time' => $timeRange ?? 0,
                            ];
                        }
                        $relationList[$relationKey]['goods_list'] = $goodsList;
                        unset($relationList[$relationKey]['base_num'], $relationList[$relationKey]['gids']);
                    }
                    $item['default_data']['unlock_num'] = $totalUnlockNum;
                    $defaultData = $item['default_data'];
                    continue;
                } else
                {
                    $unlockNumber = $orderModel->getTotalPrepaidOrder($goodType, (int)$item['srid']);
                }
            } else
            {
                $unlockNumber = $orderModel->getTotalPrepaidOrder($goodType, $item['id']);
            }

            if ((int)$item['status'] !== 2)
            {
                if ($goodType === 17)
                {
                    //  检测 是否购买过
                    $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($this->user['id'], $rid, 0, $item['srid']);
                    $unlock_status = $unlockStatus ? 2 : 0;
                } else
                    if (isset($unlockReport[$item['id']]))
                    {
                        if ((int)$unlockReport[$item['id']]['status'] === 2)
                        {
                            $unlock_status = 2;//已解锁
                        } else
                        {
                            $unlock_status = 1;//计算中
                        }
                    } else
                    {
                        $unlock_status = 0;//未解锁
                    }
            } else
            {
                $unlock_status = 3;//未开放
            }
            if ($goodType === 17)
            {
                $d = [
                    'gid' => (int)$item['id'],
                    'status' => $unlock_status,
                    'bg_img' => $item['bg_img'] ?? '',
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $item['name'] ?? '',
                    'unlock_num' => $item['base_num'] + $unlockNumber,
                    'active_time' => $timeRange ?? 0,
                    'target' => 'local',
                    'link' => $unlock_status === 0 ?
                        "synastry_report_detail?rid1={$rid}&rid2=0&srid={$srid}&need_auth=1" :    // 下单介绍页
                        "synastry_report_list?rid1={$rid}&rid2=0&srid={$srid}&need_auth=1"  // 查看合盘报告列表
                ];
            } else
            {
                $d = [
                    'gid' => (int)$item['id'],
                    'status' => $unlock_status,
                    'bg_img' => $reportImage['large'][$item['flag']] ?? '',
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
                    'unlock_num' => $item['base_num'] + $unlockNumber,
                    'active_time' => $timeRange ?? 0,
                    'target' => 'local',
                    'link' => "report_details?rid={$rid}&gid={$item['id']}&need_auth=1"
                ];
            }

            if ($d['status'] === 1)
            {   // 解锁中
                $unlockingData[] = $d;
            } elseif ($d['status'] === 0)
            {   // 未解锁
                $lockData[] = $d;
            } elseif ($d['status'] === 2)
            {   // 已解锁
                $unlockData[] = $d;
            }
        }

        // 计算 合盘报告计算开始时间 开始--------------------
        $year = date("Y", $this->request->time());
        $month = date('m', $this->request->time());
        // 下月1号0点时间戳
        $nextMonthStarttime = strtotime(date('Y-m-d', mktime(0, 0, 0, +($month + 1), 1, $year)));
        // 距离下个月1号小于等于10天时，推运时间取下个月
        if ($nextMonthStarttime - $this->request->time() <= 86400 * 10)
        {
            $startTime = $nextMonthStarttime;
        } else
        {
            $startTime = strtotime(date('Y-m-d', mktime(0, 0, 0, $month, 1, $year)));
        }
        // 计算 合盘报告计算开始时间 结束--------------------

        $result = [
            'header_bg' => $headerBg,
            'header_bg_x' => $headerBgX,
            // 'natal_report_list' => $rid ? array_merge($unlockData, $unlockingData, $lockData) : [], // 合盘暂时不显示推荐报告信息
            'natal_report_list' => [], // 暂时不显示推荐报告信息
            'relation_list' => array_values($relationList),
            'default_time' => date('Y-m', $startTime),
            'time_range' => [
                'start_time' => date('Y-m'),
                'end_time' => '2058-01',
            ],
            'default_data' => $defaultData
        ];

        return show(config('code.success'), '请求成功', $result);
    }

    /**
     * 合盘报告列表
     * @return Json
     * @throws Exception
     */
    public function getList(): Json
    {
        $rid1 = input('rid1/d', 0);
        $rid2 = input('rid2/d', 0);
        $srid = input('srid/d', 0);

        if ($srid !== 1)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($rid2)
        {
            $recodes = (new \app\common\cachemodel\Recode())->batchGetInfoByIds([$rid1, $rid2], ['uid', 'name', 'isself']);
            try
            {
                if (!$recodes[$rid1] || !$recodes[$rid2] || (int)$recodes[$rid1]['uid'] !== $this->user['id'] || (int)$recodes[$rid2]['uid'] !== $this->user['id'])
                {
                    return show(config('code.error'), '服务异常；档案不存在');
                }
            }
            catch (Exception $e)
            {
                return show(config('code.error'), '服务异常；档案不存在');
            }

            if (mb_strlen($recodes[$rid1]['name']) > 5)
            {
                $recodes[$rid1]['name'] = mb_substr($recodes[$rid1]['name'], 0, 5) . '...';
            }
            if (mb_strlen($recodes[$rid2]['name']) > 5)
            {
                $recodes[$rid2]['name'] = mb_substr($recodes[$rid2]['name'], 0, 5) . '...';
            }

            $title = ($recodes[$rid1]['isself'] ? '自己' : $recodes[$rid1]['name']) . '和' . ($recodes[$rid2]['isself'] ? '自己' : $recodes[$rid2]['name']) . '的合盘记录';
        }


        $synastryReportData = (new ZlSynastryReport())->getSynastryReportList($this->user['id'], $rid1, $rid2, $srid, (int)$this->user['rid']);

        $resData = [
            'synastry_report_list' => $synastryReportData,
            'btn_info' => [
                'name' => '创建我和TA的合盘报告',
                'target' => 'local',
                'link' => "synastry_report_detail?rid1={$rid1}&rid2={$rid2}&srid={$srid}&need_auth=1"
            ],
            'title' => $title ?? ''
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * @return Json
     * @throws Exception
     */
    public function del(): ?Json
    {
        $id = input('id/d', 0);

        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $synastryReportModel = new ZlSynastryReport();

        $reportDetail = $synastryReportModel->getInfoById($id, ['uid', 'rid1', 'rid2', 'srid']);

        if (!$reportDetail || (int)$reportDetail['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，该合盘报告不存在');
        }

        $res = $synastryReportModel->reportDel($this->user['id'], $id, (int)$reportDetail['rid1'], (int)$reportDetail['rid2'], (int)$reportDetail['srid']);

        if ($res)
        {
            return show(config('code.success'), '删除成功');
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }
}
